//
//  LXSellApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2022/1/5.
//  Copyright © 2022 LX_App. All rights reserved.
//

#import "LXSellApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXChooseBtnTableViewCell.h"
#import "KeHuInfoModel.h"
#import "LXChooseManagerViewController.h"
#import "LXRemarkTabelViewCell.h"
#import "ChoseMoRenPersonVC.h"
#import "FuZeRenModel.h"

@interface LXSellApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;
@property (nonatomic) NSArray *payWayData; // 支付方式数据源
@property (nonatomic) NSInteger payWay; // 支付方式 1全款/2分期
@property (nonatomic) NSString *liaisonPhone;// 联系人电话
@property (nonatomic) NSString *userNameSaleUserId;// 负责人id
@property (nonatomic) FuZeRenModel *fuZeModel;// 负责人模型
@property (nonatomic) MoRenLianXiRenModel *liaisonModel;// 联系人模型

@end

@implementation LXSellApplyViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.type==1) {
        [self layoutCustomNav:self.view title:@"出售详情"];
    }
    else {
        [self layoutCustomNav:self.view title:@"发布出售"];

    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerClass:[LXChooseBtnTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    
    [self loadData];
    
    if (self.type==0) {
        [self setBottomViewWithText:@"发布"];
        self.tableView.height = kScreenHeight - LL_StatusBarAndNavigationBarHeight - kComHeight;
    }
   
    
    
}

- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
   
    // 默认分期
    self.payWay = 2;

    
    [self.loanDic setValue:self.carModel.carNum forKey:@"carNum"];
    
    // type == 1 说明从车辆详情进入
    if (self.type==1) {

        // 车牌号
        [self.loanDic setValue:self.carModel.carNum forKey:@"carNum"];
       
        
        // 过户次数
        [self.loanDic setValue:self.carModel.transferCount forKey:@"transferCount"];
        // 联系人
        [self.loanDic setValue:self.carModel.customName forKey:@"liaisonName"];
        // 负责人
        [self.loanDic setValue:self.carModel.userNameSale forKey:@"userNameSale"];
        // 总金额
        [self.loanDic setValue:[NSString stringWithFormat:@"%.2lf",[self.carModel.priceSum doubleValue]] forKey:@"priceSum"];
        // 付款方式
        if ([self.carModel.payWay intValue] == 0) {
            self.payWay = 1;
        }
        else {
            self.payWay = 2;
        }
        
        // 首付
        [self.loanDic setValue:[NSString stringWithFormat:@"%.2lf",[self.carModel.rent doubleValue]] forKey:@"firstPay"];
        // 月供
        [self.loanDic setValue:[NSString stringWithFormat:@"%.2lf",[self.carModel.monthPay doubleValue]] forKey:@"monthPay"];
        // 期数
        [self.loanDic setValue:self.carModel.payCount forKey:@"payCount"];
        // 分期总金额
        [self.loanDic setValue:[NSString stringWithFormat:@"%.2lf",[self.carModel.priceSum doubleValue]] forKey:@"priceSumStr"];
        // 使用年限
        [self.loanDic setValue:self.carModel.useYear forKey:@"useYear"];
        // 已发布
        [self.loanDic setValue:self.carModel.timeDay forKey:@"timeDay"];
        // 购车客户
        [self.loanDic setValue:self.carModel.customerName forKey:@"customerName"];
        
        // 备注
        [self.loanDic setValue:self.carModel.remark forKey:@"remark"];

    
    }
    
    
   
    
    
    
    self.data = @[
        @{
            @"title":@"车牌号",
            @"key":@"carNum",
            @"placeHolder" : @"请输入车牌号",
            @"canEdit":@(NO),
            @"detailTextColor" : mainColor,
            @"showAccess":@(NO),
            @"maxLength":@(8),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"过户次数",
            @"key":@"transferCount",
            @"placeHolder" : @"请选择过户次数",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(NO):@(YES),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"":@"clickTransferCount",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"联系人",
            @"key":@"liaisonName",
            @"placeHolder" : self.type==1?@"-":@"请选择默认联系人",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(NO):@(YES),
            @"maxLength":@(25),
            @"sel":self.type==1?@"":@"clickLiaisonName",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"负责人",
            @"key":@"userNameSale",
            @"placeHolder" : @"请选择负责人",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(NO):@(YES),
            @"maxLength":@(1000),
            @"sel":self.type==1?@"":@"clickUserNameSale",
            @"height":self.type==1?@(0.00001):@(kComHeight)
        },
        @{
            @"title":@"总金额",
            @"key":@"priceSum",
            @"placeHolder" : @"请输入金额",
            @"showUnit" : @"元",
            @"detailTextColor" : self.type==1?[UIColor colorWithHexString:@"#EA545A"]:nil,
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"canEdit":self.type==1?@(NO):@(YES),
            @"showAccess":@(NO),
            @"maxLength":@(10),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"支付方式",
            @"key":@"payWay",
            @"height":@([LXChooseBtnTableViewCell height:self.payWayData]),
            @"canEdit":self.type==1?@(NO):@(YES),
        },
        @{
            @"title":@"首付",
            @"key":@"firstPay",
            @"placeHolder" : @"请输入首付金额",
            @"detailTextColor" : self.type==1?[UIColor colorWithHexString:@"#EA545A"]:nil,
            @"showUnit" : @"元",
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"canEdit":self.type==1?@(NO):@(YES),
            @"showAccess":@(NO),
            @"maxLength":@(10),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"月供",
            @"key":@"monthPay",
            @"placeHolder" : @"请输入月供金额",
            @"detailTextColor" : self.type==1?[UIColor colorWithHexString:@"#EA545A"]:nil,
            @"showUnit" : @"元",
            @"keyboardType":@(UIKeyboardTypeDecimalPad),
            @"canEdit":self.type==1?@(NO):@(YES),
            @"showAccess":@(NO),
            @"maxLength":@(7),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"分期",
            @"key":@"payCount",
            @"placeHolder" : @"请输入分期期数",
            @"detailTextColor" : self.type==1?[UIColor colorWithHexString:@"#EA545A"]:nil,
            @"showUnit" : @"期",
            @"keyboardType":@(UIKeyboardTypeNumberPad),
            @"canEdit":self.type==1?@(NO):@(YES),
            @"showAccess":@(NO),
            @"maxLength":@(2),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"分期总金额",
            @"key":@"priceSumStr",
            @"placeHolder" : @"自动计算",
            @"detailTextColor" : self.type==1?[UIColor colorWithHexString:@"#EA545A"]:nil,
            @"showUnit" : @"元",
            @"keyboardType":@(UIKeyboardTypeNamePhonePad),
            @"canEdit":@(NO),
            @"showAccess":@(NO),
            @"maxLength":@(3),
            @"sel":@"",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"车牌使用年限",
            @"key":@"useYear",
            @"placeHolder" : @"请选择车牌使用年限",
            @"canEdit":@(NO),
            @"showAccess":self.type==1?@(NO):@(YES),
            @"maxLength":@(3),
            @"sel":self.type==1?@"":@"clickUseYear",
            @"height":@(kComHeight)
        },
        @{
            @"title":@"已发布",
            @"key":@"timeDay",
            @"placeHolder" : @"0",
            @"showUnit" : @"天",
            @"canEdit":@(NO),
            @"showAccess":@(NO),
            @"maxLength":@(3),
            @"sel":@"",
            @"height":self.type==1?@(kComHeight):@(0.000001)
        },
        @{
            @"title":@"购车客户",
            @"key":@"customerName",
            @"placeHolder" : @"",
            @"canEdit":@(NO),
            @"showAccess":@(NO),
            @"maxLength":@(3),
            @"sel":@"",
            @"height":self.type==1?@(kComHeight):@(0.000001)
        },
        
        @{
            @"title":@"备注",
            @"key":@"remark",
            @"height":@(180),
        },
       
 ].mutableCopy;
    
    
    [self.tableView reloadData];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];

    // 保养内容
    if([dic[@"key"]  isEqualToString:@"remark"]){
       LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
       cell.selectionStyle = UITableViewCellSelectionStyleNone;
       [cell setClipsToBounds:YES];
       cell.textView.placeholder = @"请输入 ~";
       cell.textView.maxLength = 200;
        cell.textView.userInteractionEnabled = self.type==1?NO:YES;
       cell.remarkTitle.text = dic[@"title"];
       cell.textView.text = self.loanDic[dic[@"key"]];
       [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
           self.loanDic[dic[@"key"]]  = textStr;
       }];
       return cell;
   }
    // 支付方式
    else if ([dic[@"key"] isEqualToString:@"payWay"]) {
       
        
        LXChooseBtnTableViewCell *cell = [[LXChooseBtnTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXChooseBtnTableViewCell class]) WithData:self.payWayData];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.canEdit = self.type==1?NO:YES;
        cell.titleLab.text = dic[@"title"];
        [cell setClickBtnBlock:^(NSInteger Id) {
            self.payWay = Id;
        }];
        
        return cell;
    }
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    __block LXTableViewCell *blockCell = cell;
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        // 分期期数
        if ([dic[@"key"] isEqualToString:@"payCount"]) {
            if ([textStr intValue]>60) {
                textStr = @"60";
                blockCell.textFiled.text = textStr;
                showAlert(@"分期不能大于60期");
            }
        }
        
        self.loanDic[dic[@"key"]]  = textStr;
        // 分期期数 * 月供 + 首付
        if ([dic[@"key"] isEqualToString:@"payCount"]||
            [dic[@"key"] isEqualToString:@"monthPay"]||
            [dic[@"key"] isEqualToString:@"firstPay"]) {
            // 分期期数 * 月供 + 首付
            double priceSumStr = ([self.loanDic[@"payCount"] intValue]  *  [self.loanDic[@"monthPay"] doubleValue]) + [self.loanDic[@"firstPay"] doubleValue];
            [self.loanDic setValue:[NSString stringWithFormat:@"%.2lf",priceSumStr] forKey:@"priceSumStr"];
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.data.count-5 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            
        }
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}

#pragma mark -- 选择过户次数
-(void)clickTransferCount{
    [self.view endEditing:YES];
    
    
    NSArray *ghcsAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_GHCS];
    NSMutableArray *ary = [NSMutableArray array];
    for (NSDictionary *dic in ghcsAry) {
        [ary addObject:dic[@"label"]];
    }
        
    SinglePickerView *singPickView = [[SinglePickerView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    for (int i = 0; i<ary.count; i++) {
        if ([self.loanDic[@"transferCount"] isEqualToString:ary[i]]) {
            singPickView.selectInteger = i;
        }
    }
    [singPickView pickViewWithArray:ary andDescArray:nil andTitleStr:@"请选择过户次数"];
    [[UIApplication sharedApplication].delegate.window addSubview:singPickView];
    [singPickView showBottomView];
    singPickView.block = ^(NSString *singleTitle){
        [self.loanDic setObject:singleTitle forKey:self.selDic[@"key"]];
        [self.tableView reloadData];
    };
   
}
#pragma mark -- 选择联系人
- (void)clickLiaisonName{
    [self.view endEditing:YES];
    
    
    ChoseMoRenPersonVC  *vc = [[ChoseMoRenPersonVC alloc] init];
    [vc setToSendValue:^(MoRenLianXiRenModel * _Nonnull model) {
        [self.loanDic setValue:model.name forKey:@"liaisonName"];
        self.liaisonModel = model;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];

}

#pragma mark -- 选择负责人
-(void)clickUserNameSale{
 
    [self.view endEditing:YES];
    
    LXChooseManagerViewController *vc = [[LXChooseManagerViewController alloc] init];
    WEAKSELF
    [vc setToSendValue:^(FuZeRenModel * _Nonnull model) {
        [weakSelf.loanDic setValue:model.realName forKey:@"userNameSale"];
        weakSelf.userNameSaleUserId = model.ID;
        weakSelf.fuZeModel = model;
        [weakSelf.tableView reloadData];
    }];
    vc.model = self.fuZeModel;
    [self pushToNextController:vc];
    
}

#pragma mark -- 选择车牌使用年限
-(void)clickUseYear{
    [self.view endEditing:YES];
//    NSArray *synxAry = [[NSUserDefaults standardUserDefaults] valueForKey:k_SYNX];
//    NSMutableArray *ary = [NSMutableArray array];
//    for (NSDictionary *dic in synxAry) {
//        [ary addObject:[dic[@"value"] stringByAppendingString:@"年"]];
//    }
//
//    SinglePickerView *singPickView = [[SinglePickerView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//    for (int i = 0; i<ary.count; i++) {
//        if ([self.loanDic[@"useYear"] isEqualToString:ary[i]]) {
//            singPickView.selectInteger = i;
//        }
//    }
//    [singPickView pickViewWithArray:ary andDescArray:nil andTitleStr:@"请选择车牌使用年限"];
//    [[UIApplication sharedApplication].delegate.window addSubview:singPickView];
//    [singPickView showBottomView];
//    singPickView.block = ^(NSString *singleTitle){
//        [self.loanDic setObject:singleTitle forKey:self.selDic[@"key"]];
//        [self.tableView reloadData];
//    };
    
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"useYear"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择车牌使用年限"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
    };
    
    
}



-(void)clickBottomView:(UIButton *)sender{
    

    if (StringIsEmpty(self.loanDic[@"carNum"])){
        showAlert(@"车牌号不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"transferCount"])){
        showAlert(@"请选择过户次数");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"liaisonName"])){
        showAlert(@"联系人不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"userNameSale"])){
        showAlert(@"负责人不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"priceSum"])){
        showAlert(@"总金额不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"firstPay"])){
        showAlert(@"首付不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"monthPay"])){
        showAlert(@"月供不能为空");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"payCount"])){
        showAlert(@"分期不能为空");
        return;
    }
    
    if (StringIsEmpty(self.loanDic[@"useYear"])){
        showAlert(@"请选择车牌使用年限");
        return;
    }
    
    
    NSDictionary *dic = @{
        
        @"carId":self.carModel.ID, // 车辆id
        @"carNum":self.loanDic[@"carNum"],// 车牌号
        @"transferCount": [self.loanDic[@"transferCount"] substringToIndex:1],// 过户次数
        @"liaisonId":self.liaisonModel.ID,// 联系人ID
        @"liaisonName":self.liaisonModel.name,// 联系人
        @"liaisonPhone":self.liaisonModel.telePhone,// 联系人电话
        @"userNameSale":self.loanDic[@"userNameSale"],// 负责人
        @"userNameSaleUserId":self.userNameSaleUserId,// 负责人id
        @"priceSum":self.loanDic[@"priceSum"],// 总金额
        @"payWay":@(self.payWay),// 支付方式
        @"firstPay":self.loanDic[@"firstPay"],// 首付
        @"monthPay":self.loanDic[@"monthPay"],// 月供
        @"payCount":self.loanDic[@"payCount"],// 分期
        @"useYear":self.loanDic[@"useYear"],// 车牌使用年限
        @"remark":self.loanDic[@"remark"],// 备注
    };

    [Tool showAlertTitle:@"您确定发布吗?" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        [MSNetworkManager postRevertUrl:Sale_URL params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                showAlert(@"车辆出售成功");
                [self.navigationController popViewControllerAnimated:YES];
            }
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
            
        } withShowHud:YES];
        
    } onVC:self];

   

    
}


#pragma mark --  支付方式数据源
- (NSArray *)payWayData{

    _payWayData = @[
        @{
            @"title":@"分期",
            @"sel":@(NO),
            @"id":@"2"
        }.mutableCopy,
//        @{
//            @"title":@"全款",
//            @"sel":@(NO),
//            @"id":@"1"
//        }.mutableCopy,
    ];
    for (NSMutableDictionary *dic in _payWayData) {
        if ([dic[@"id"] intValue] == self.payWay) {
            [dic setValue:@(YES) forKey:@"sel"];
            break;
        }
    }
    return _payWayData;
}

- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, LL_StatusBarAndNavigationBarHeight, ScreenWidth, kScreenHeight - LL_StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(0,0,kComHeight + 10,0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tableView;
}

@end

